<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm ref="filterForm" noimmediate hand :elements="filterElements" @submit="handleSearch"
        @reset="handleReset" />
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer style="margin-bottom: 10px">
        <!-- <Button style="margin-right: 12px" @click="actionUnfoldFunc(true)"
          >导出</Button
        > -->
      </OperationContainer>
      <div class="table-box1">
        <el-table ref="ctab" v-loading="topTableLoading" :data="topTable" border
          :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }" header-row-class-name="ck-table-header"
          row-class-name="ck-table-row" size="small" row-key="code" height="100%" show-summary
          :summary-method="getSummaries">
          <el-table-column label="项目名称" prop="deptName" />
          <el-table-column label="收益" prop="proceeds">
            <template slot-scope="scope">
              {{ scope.row.proceeds | numberToCurrency }}
            </template>
          </el-table-column>
          <el-table-column label="比例" prop="proceedProportion" />
        </el-table>
      </div>

      <div class="table-box2">
        <el-table ref="tableref" v-loading="tableLoading" :data="tableData" border
          :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }" header-row-class-name="ck-table-header"
          row-class-name="ck-table-row" size="small" row-key="code" height="100%" show-summary
          :summary-method="getSummariesBottom">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column label="科室代码" prop="deptCode" />
          <el-table-column label="科室名称" prop="deptName" />
          <el-table-column label="金额" prop="proceeds">
            <template slot-scope="scope">
              {{ scope.row.proceeds | numberToCurrency }}
            </template>
          </el-table-column>
          <el-table-column label="比例" prop="proceedProportion" />
        </el-table>
      </div>
      <!-- 分页 -->
      <!-- <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      /> -->
    </Container>
  </ContainerGroup>
</template>

<script>
import {
  listDeptProfitByDateAndPDept,
  listDeptProfitCompositionByDateAndPDept,
} from "@/utils/apis/deptDirectorAnalysis";
import { getCostDepartments } from "@/utils/apis/accountingUnit/corres";
export default {
  name: "incomeAnalysis",
  data() {
    return {
      filterElements: [
        {
          key: "yearMonth",
          label: "年/月",
          mode: "monthrange",
          type: "date-picker",
          format: "yyyy-MM",
          value: [this.$util.currentDate(), this.$util.currentDate()],
          width: 340,
        },
        {
          key: "deptCode",
          type: "Select",
          label: "科室",
          value: "",
          width: 210,
          itemLabel: "deptName",
          itemValue: "deptCode",
          options: [],
        },
      ],
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
      tableData: [],
      tableData1: [],
      tableLoading: false,
      newParamList: {},
      topTableLoading: false,
      topTable: [],
    };
  },
  updated() {
    if (this.$refs.tableref) {
      this.$refs.tableref.doLayout();
    }
    if (this.$refs.ctab) {
      this.$refs.ctab.doLayout();
    }
  },
  created() {
    this.getSelect();
  },
  methods: {
    // 指定列求和
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (index >= 1) {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = sums[index].toFixed(2);
            // sums[index] += " 元";
          } else {
            sums[index] = "N/A";
          }
        }
      });
      return sums;
    },
    getSummariesBottom(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (index > 2) {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = sums[index].toFixed(2);
            // sums[index] += " 元";
          } else {
            sums[index] = "N/A";
          }
        }
      });
      return sums;
    },
    getSelect() {
      getCostDepartments({
        isParent: true,
        projectId: "1",
        isLike: true,
      }).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[1].options = res.data.data;
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.filterForm.handleForceSet({
                deptCode: res.data.data[0] && res.data.data[0].deptCode,
              });
              this.newParamList = this.$refs.filterForm.getParms();
              this.getData();
              this.getDataList();
            });
          }, 500);
        }
      });
    },
    // 分页
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page;
      this.pageAttr.pageSize = payload.pageSize;
      this.getData();
      this.getDataList();
    },
    handleSearch(value) {
      this.newParamList = value;
      this.pageAttr.currentPage = 1;
      this.getData();
      this.getDataList();
    },
    handleReset(value) {
      // location.reload();
      this.$refs.filterForm.handleForceSet({
        yearMonth: [this.$util.currentDate(), this.$util.currentDate()],
        deptCode:
          this.filterElements[1].options &&
          this.filterElements[1].options[0].deptCode,
      });
      const obj = {};
      value.forEach((item) => {
        obj[item.key] = item.value;
      });
      this.newParamList = obj;
      this.getData();
    },
    createNewData() { },
    getData() {
      // 列表
      if (this.commParams().currentYear != this.commParams().endcurrentYear) {
        this.$message.warning("不能选择跨年时间段");
        return;
      }
      this.tableLoading = true;
      this.tableData = [];
      listDeptProfitByDateAndPDept(
        this.commParams().param,
        this.newParamList.deptCode
      ).then((res) => {
        this.tableLoading = false;
        if (res.data.code === 200) {
          this.tableData = res.data.data;
        }
      });
    },
    getDataList() {
      if (this.commParams().currentYear != this.commParams().endcurrentYear) {
        this.$message.warning("不能选择跨年时间段");
        return;
      }
      this.topTableLoading = true;
      listDeptProfitCompositionByDateAndPDept(
        this.commParams().param,
        this.newParamList.deptCode
      ).then((res) => {
        this.topTableLoading = false;
        if (res.data.code === 200) {
          this.topTable = res.data.data;
        }
      });
    },
    commParams() {
      const startYearMonth =
        this.newParamList.yearMonth && this.newParamList.yearMonth[0];
      const endYearMonth =
        this.newParamList.yearMonth && this.newParamList.yearMonth[1];
      let currentYear = new Date(startYearMonth).getFullYear();
      let currentMonth = new Date(startYearMonth).getMonth() + 1;

      let endcurrentYear = new Date(endYearMonth).getFullYear();
      let endcurrentMonth = new Date(endYearMonth).getMonth() + 1;
      let param = {
        endYear: endcurrentYear,
        endMonth: endcurrentMonth,
        starMonth: this.formatNumber(currentMonth),
        starYear: currentYear,
        yard: "1",
      };
      return {
        param: param,
        currentYear: currentYear,
        endcurrentYear: endcurrentYear,
      };
    },
    formatNumber(n) {
      n = n.toString();
      return n[1] ? n : `0${n}`;
    },
  },
};
</script>

<style lang="less" scoped>
.table-box1 {
  height: 200px;
  margin-bottom: 20px;
}

.table-box2 {
  height: 50vh;
}

.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}

.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}

.text-btn {
  color: #2165f9;
  border-bottom: 1px solid #2165f9;
  display: inline-block !important;
  cursor: pointer;
}
</style>
